﻿// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Collections.Generic;

namespace SnapObjects.Data.Odbc
{
    internal class OdbcSqlAnywhereProcedureParameterSchemaProvider : OdbcSqlAnywhereParameterSchemaProvider
    {
        public OdbcSqlAnywhereProcedureParameterSchemaProvider(DataContext dataContext) : base(dataContext)
        {
        }

        protected override ProcedureSchema CreateParameterSchema(
            string name, 
            IReadOnlyList<AdoDbParameter> adoDbParameters,
            IReadOnlyList<DynamicModel> dbParameters)
        {
            return new ProcedureSchema(name, adoDbParameters);
        }

        protected override string GetCheckUserQuerySql(string name)
        {
            var sql = @"
SELECT proc_name 
  FROM sysprocedure p
 INNER JOIN sysusers u 
    ON p.creator = u.uid
 WHERE (lower(left(p.proc_defn, 15)) <> 'create function' or p.proc_defn is null) 
   AND lower(proc_name) = lower('{0}') AND u.uid = user_id() ";

            return String.Format(sql, name);
        }

        protected override string GetSchemaQuerySql(string name, string condition)
        {
            var sql = @"
SELECT pro.proc_id as object_uniqueidentifier,
       parm.parm_name as parameter_name, 
       domain.domain_name as parameter_datatype,
       CASE parm.parm_mode_out WHEN 'N' THEN 'IN' ELSE 'OUT' END as parameter_mode,
       parm.width as parameter_precision,
       parm.scale as parameter_scale,
       parm.[default] as parameter_defaultvalue
  FROM sysprocedure pro 
 INNER JOIN sysusers u 
    ON pro.creator = u.uid 
  LEFT JOIN sysprocparm parm 
    ON pro.proc_id = parm.proc_id AND parm.parm_type = 0
  LEFT join sysdomain domain
    on parm.domain_id = domain.domain_id
 WHERE (lower(left(pro.proc_defn, 15)) <> 'create function' or pro.proc_defn is null) 
   AND lower(pro.proc_name) = lower('{0}') {1}
 ORDER BY parm.parm_id";

            return String.Format(sql, name, condition);
        }
    }
}
